<template>
  <base-breadcrumb>
    <searchData :searchData="searchArr" @search="search" />
    <a-card style="height: calc(100% - 96px); overflow-y: auto;">
      <div v-if="loading" style="margin: 80px;">
        <a-spin size="large">
          <a-icon slot="indicator" type="loading" spin />
        </a-spin>
      </div>
      <div v-else-if="treeData && !!treeData.length">
        <a-space>
          <a-button v-btnPermission="'sy_012_unf_04'" type="primary" size="small" @click="onExpandAll(true)">全部展开</a-button>
          <a-button v-btnPermission="'sy_012_pac_05'" type="primary" size="small" @click="onExpandAll(false)">全部收起</a-button>
        </a-space>
        <a-tree
          :tree-data="!!searchValue ? searchTreeData : treeData"
          :expanded-keys="expandedKeys"
          :auto-expand-parent="autoExpandParent"
          :replace-fields="{
            title: 'name',
            key: 'id',
          }"
          @expand="onExpand"
          @select="onSelect"
        >
          <template slot="name" slot-scope="scope">
            <span v-if="[0, 1, 2, 3, 4].some(i => i == scope.type)" style="color: #aaa;">{{scope.name}}</span>
            <a-popover
              v-else-if="(scope.type == 7 || scope.type == 5) && popoverCon(scope).length > 0"
              destroyTooltipOnHide
            >
              <template slot="content">
                <a-button
                  v-for="item in popoverCon(scope)"
                  class="popover_btn"
                  v-btnPermission="item.permission"
                  :key="item.key"
                  type="link"
                  size="small"
                  @click="item.key === popoverButtons[0].key ? onMultipleLotsSet(scope) : item.key === popoverButtons[1].key ? onProjectGroupSet(scope) : onRemove(scope)"
                >{{item.title}}</a-button>
              </template>
              <span v-html="$options.filters.filterProjectName(scope.name, scope, $data._this)"></span>
            </a-popover>
            <span v-else v-html="$options.filters.filterProjectName(scope.name, scope, $data._this)"></span>
          </template>
        </a-tree>
      </div>
      <a-empty v-else style="padding: 100px 0;" />
    </a-card>
    <MultipleLotsSetModal :visible.sync="multipleLotsSetModalVisible" :defaultData="currentSetData" @submit="onMultipleLotsSubmit" />
    <ProjectGroupSetModal :visible.sync="projectGroupSetModalVisible" :defaultData="currentSetData" @submit="onProjectGroupSubmit" />
  </base-breadcrumb>
</template>

<script>
import { mapGetters } from 'vuex'
import { Empty, Space, Popover } from 'ant-design-vue'
import { generateList, getParentKeys, findNodeFromTree } from '@/utils/util'
import MultipleLotsSetModal from './MultipleLotsSetModal.vue'
import ProjectGroupSetModal from './ProjectGroupSetModal.vue'
import { getRelationProject, deleteSection, deleteProjectGroup } from '@/api/system/system'
import { popoverButtons, projectBelongs } from './eum.js'

const findProjectCategory = (dataList, current) => {
  const findData = dataList.find(item => item.id === current.parentId)
  if(!!findData && projectBelongs.some(item => item.key == findData.type)){
    return findData
  }
  if(!!findData && !projectBelongs.some(item => item.key == findData.type)){
    return findProjectCategory(dataList, findData)
  }
  return null
}

export default {
  components: {
    AEmpty: Empty,
    ASpace: Space,
    APopover: Popover,
    MultipleLotsSetModal,
    ProjectGroupSetModal,
  },
  data(){
    return {
      _this: this,
      searchArr: [
        {
          name: '名称',
          value: 'name',
          type: 'input'
        }
      ],
      loading: false,
      treeData: [],
      expandedKeys: [],
      autoExpandParent: true,
      popoverButtons,
      popoverCon: (event) => {
        const { dataRef } = event
        const permission = popoverButtons.map(item => this.btnPermission.find(i => i.code === item.permission))
        const isShow1 = !!permission[0] || !!permission[1]
        const isShow2 = !!permission[2]
        const isShow3 = isShow1 || isShow2
        const isShow4 = !!permission[0] || !!permission[2]
        const findProject = findProjectCategory(this.treeDataList, dataRef)
        // 独立项目
        if(!!findProject && findProject.type == 0 && dataRef.type == 7){
          return isShow1 ? [popoverButtons[0], popoverButtons[1]] : []
        }
        // 总分包项目
        if(!!findProject && findProject.type == 1 && dataRef.type == 7){
          return isShow1 ? [popoverButtons[0], popoverButtons[1]] : []
        }
        // 多标段项目
        if(!!findProject && findProject.type == 2){
          return dataRef.type == 7 ? (
            isShow1 ? [popoverButtons[0], popoverButtons[1]] : []
          ) : (
            isShow2 ? [popoverButtons[2]] : []
          )
        }
        // 项目群
        if(!!findProject && findProject.type == 3){
          if(dataRef.type == 5){
            return isShow2 ? [popoverButtons[2]] : []
          }
          const group = this.treeDataList.filter(item => item.parentId === dataRef.parentId)
          return group.findIndex(item => item.id === dataRef.id) === 0 ? (
            isShow3 ? popoverButtons : []
          ) : (
            isShow4 ? [popoverButtons[0], popoverButtons[2]] : []
          )
        }
        // 也是项目群，复合项目下的项目群
        const groupProject = this.treeDataList.find(item => item.id === dataRef.parentId)
        if(!!findProject && findProject.type == 4 && !!groupProject && groupProject.name.indexOf('指挥部') > -1){
          if(dataRef.type == 5){
            return isShow2 ? [popoverButtons[2]] : []
          }
          const group = this.treeDataList.filter(item => item.parentId === dataRef.parentId)
          return group.findIndex(item => item.id === dataRef.id) === 0 ? (
            isShow3 ? popoverButtons : []
          ) : (
            isShow4 ? [popoverButtons[0], popoverButtons[2]] : []
          )
        }
        // 复合项目
        if(!!findProject && findProject.type == 4){
          return dataRef.type == 7 ? (
            isShow1 ? [popoverButtons[0], popoverButtons[1]] : []
          ) : (
            isShow2 ? [popoverButtons[2]] : []
          )
        }
        return []
      },
      multipleLotsSetModalVisible: false,
      projectGroupSetModalVisible: false,
      currentSetData: null,
      searchValue: '',
    }
  },
  computed: {
    ...mapGetters(['btnPermission']),
    treeDataList(){
      return generateList(this.treeData)
    }
  },
  created(){
    this.getTreeData()
  },
  filters: {
    filterProjectName(text, scope, _this){
      const { dataRef } = scope
      const findProject = findProjectCategory(_this.treeDataList, dataRef)
      let searchHtml = `<span style="display: inline-block; max-width: calc(100% - 100px);">${text}</span>`
      if(_this.searchValue && text.indexOf(_this.searchValue) > -1){
        searchHtml = `<span style="display: inline-block; max-width: calc(100% - 100px);">${text.substr(0, text.indexOf(_this.searchValue))}
          <span style="color: #f50;">
          ${_this.searchValue}</span>${text.substr(text.indexOf(_this.searchValue) + _this.searchValue.length)}</span>`
      }
      if(!!findProject && (findProject.type == 2 || findProject.type == 4) && dataRef.type == 5){
        const parent = findNodeFromTree(_this.searchValue ? _this.searchTreeData : _this.treeData, { key: 'id', value: dataRef.parentId })
        const nodes = parent && parent.children ? parent.children.filter(item => item.type == 5) : []
        return `<span style="display: inline-block; color: #aaa; vertical-align: top;">标段${nodes.findIndex(item => item.id === dataRef.id) + 1}：</span>${searchHtml}`
      }
      if(!!findProject && findProject.type == 3 && dataRef.type == 7){
        const parent = findNodeFromTree(_this.searchValue ? _this.searchTreeData : _this.treeData, { key: 'id', value: dataRef.parentId })
        const nodes = parent && parent.children ? parent.children.filter(item => item.type == 7) : []
        return `<span style="display: inline-block; color: #aaa; vertical-align: top;">项目${nodes.findIndex(item => item.id === dataRef.id) + 1}：</span>${searchHtml}`
      }
      if(!!findProject && findProject.type == 4 && text.indexOf('指挥部') == -1){
        const parent = findNodeFromTree(_this.searchValue ? _this.searchTreeData : _this.treeData, { key: 'id', value: dataRef.parentId })
        if(parent && parent.name.indexOf('指挥部') > -1 && !!parent.children.length){
          const nodes = parent && parent.children ? parent.children.filter(item => item.type == 7) : []
          return `<span style="display: inline-block; color: #aaa; vertical-align: top;">项目${nodes.findIndex(item => item.id === dataRef.id) + 1}：</span>${searchHtml}`
        }
      }
      if(text && text.indexOf('指挥部') > -1){
        return `<span style="color: #aaa;">${searchHtml}</span>`
      }
      if(/内部分包(.+)：/.test(searchHtml)){
        return searchHtml.replace(/内部分包(.+)：/, `<span style="color: #aaa;">${searchHtml.match(/内部分包(.+)：/)[0]}</span>`)
      }
      return searchHtml
    }
  },
  methods: {
    // 获取树数据，0:独立项目/1:总分包项目/2:多标段项目/3:项目群/4:复合项目/5:标段/6：内部分包/7：项目
    getTreeData(){
      this.loading = true
      getRelationProject().then(res => {
        if(res.code == 200){
          this.treeData = !!res.data ? [res.data] : []
          this.searchTreeData = this.treeData
          this.filterTreeData()
          this.expandedKeys = this.treeDataList.map(item => item.id)
        }
        this.loading = false
        this.$forceUpdate()
      }).catch(() => {
        this.loading = false
      })
    },
    filterTreeData(){
      const fun = (list) => {
        return list.map(item => {
          return item.children && !!item.children.length ? {
            ...item,
            scopedSlots: { title: 'name', type: 'type' },
            children: fun(item.children)
          } : {
            ...item,
            scopedSlots: { title: 'name', type: 'type' },
          }
        })
      }
      this.treeData = fun(this.treeData)
    },
    // 搜索
    search(event){
      let expandedKeys = []
      this.treeDataList.forEach(item => {
        if((item.name || '').indexOf(event.name) > -1){
          expandedKeys = [
            ...expandedKeys,
            ...getParentKeys(this.treeData, { value: item.id })
          ]
        }
      })
      Object.assign(this, {
        expandedKeys: !!event.name ? expandedKeys : this.treeDataList.map(item => item.id),
        searchValue: event.name,
        autoExpandParent: !!this.searchValue,
      })
      this.searchTreeData = !!this.searchValue ? this.searchFilterTreeData(this.treeData) : this.treeData
    },
    searchFilterTreeData(data){
      data = data || this.treeData
      return data.filter(item => this.expandedKeys.some(key => key === item.id) || item.name.indexOf(this.searchValue) > -1).map(item => {
        if (item.children && item.children.length) {
          return {
            ...item,
            children: this.searchFilterTreeData(item.children)
          }
        } 
        return item
      })
    },
    // 树全部展开收起
    onExpandAll(isExpand){
      if(isExpand){
        this.expandedKeys = this.treeDataList.map(item => item.id)
      }else{
        this.expandedKeys = []
      }
    },
    onExpand(keys){
      this.expandedKeys = keys
      this.autoExpandParent = false
    },
    onSelect(_, { node }){
      console.log(node.dataRef)
    },
    onMultipleLotsSet({ dataRef }){
      this.currentSetData = {
        ...dataRef,
        belongType: findProjectCategory(this.treeDataList, dataRef)?.type
      }
      this.multipleLotsSetModalVisible = true
    },
    onProjectGroupSet({ dataRef }){
      const belongType = findProjectCategory(this.treeDataList, dataRef)?.type
      this.currentSetData = {
        ...dataRef,
        belongType,
      }
      this.projectGroupSetModalVisible = true
    },
    onRemove({ dataRef }){
      this.$confirm({
        content: '是否确定解除',
        onOk:() => {
          return new Promise((resolve, reject) => {
            if(dataRef.type == 5){
              deleteSection({
                moreSectionIds: [dataRef.id]
              }).then(res => {
                if(res.data.code == 200){
                  this.$message.success('解除成功')
                }
                resolve()
                this.getTreeData()
              }).catch(() => {
                resolve()
              })
            }
            if(dataRef.type == 7){
              deleteProjectGroup({
                relationProjectIds: [dataRef.id]
              }).then(res => {
                if(res.data.code == 200){
                  this.$message.success('解除成功')
                }
                resolve()
                this.getTreeData()
              }).catch(() => {
                resolve()
              })
            }
          })
        }
      })
    },
    onMultipleLotsSubmit(){
      this.getTreeData()
    },
    onProjectGroupSubmit(){
      this.getTreeData()
    }
  }
}
</script>
<style lang="less" scoped>
:deep(.ant-tree li .ant-tree-node-content-wrapper){
  // white-space: break-spaces;
  height: auto;
  min-height: 24px;
  width: calc(100% - 80px);
}
</style>